package com.air;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import static org.testng.Assert.fail;

/**
 * User: Aruna Rajapaksha
 */

public class Base {

    private final Logger logger = Logger.getLogger(getClass());

    protected static StringBuffer verificationErrors = new StringBuffer();
    protected static String DELIMITER;
    protected Properties properties;
    protected String actual;
    protected String expected;
    protected String message;
    protected boolean condition;

    public Base() {
        properties = new Properties();
        try {
            properties.load(new FileInputStream("src/test/resources/test.properties"));
            DELIMITER = properties.getProperty("DELIMITER");
        } catch (IOException e) {
            logger.fatal(e);
            System.exit(0);
        } catch (Exception e) {
            logger.fatal(e);
            System.exit(0);
        }
    }

    protected void verifyErrors() {
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        }
    }

    public static JSONObject[][] getData(String fileName) {

        String csvFile = "src\\test\\resources\\data\\" + fileName;
        BufferedReader br = null;
        String line;
        String cvsSplitBy = ",";
        String[] header;
        JSONObject[][] data = null;
        List<String> rows = new ArrayList<String>();

        try {
            br = new BufferedReader(new FileReader(csvFile));

            while ((line = br.readLine()) != null) {
                rows.add(line);
            }

            header = rows.get(0).split(cvsSplitBy);
            data = new JSONObject[rows.size() - 1][1];

            for (int i = 1; i < rows.size(); i++) {
                String[] row = rows.get(i).split(cvsSplitBy);
                JSONObject record = new JSONObject();

                for (int j = 0; j < header.length; j++) {
                    try {
                        record.put(header[j], row[j]);
                    } catch (ArrayIndexOutOfBoundsException e) {
                        record.put(header[j], "");
                    }
                }
                data[i - 1][0] = record;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return data;
    }
}
